package com.oj.service.impl;

import com.oj.entity.Message;
import com.oj.entity.Tags;
import com.oj.entity.Tagsview;
import com.oj.mapper.TagsMapper;
import com.oj.mapper.TagsviewMapper;
import com.oj.service.TagsService;
import com.oj.util.MyFreeMarker;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class TagsServiceImpl implements TagsService {
    @Autowired
    FreeMarkerConfigurer freeMarkerConfigurer;

    @Autowired
    private TagsMapper tagsMapper;

    @Autowired
    private TagsviewMapper tagsviewMapper;

    public void topTagsGenerator() {
        try {
            List<Tags> tags = new ArrayList<Tags>();
            List<Tagsview> tagsViews = tagsviewMapper.queryList();
            for(Tagsview tw:tagsViews){
                Tags t = tagsMapper.query(tw.getTag_id());
                if (t == null) {
                    continue;
                }
                List<Tagsview> tagsViews_ = tagsviewMapper.queryByTagId(tw.getTag_id());
                t.setCount(tagsViews_.size());
                tagsMapper.update(t);
                tags.add(t);
            }

            Map mapTags = new HashMap();
            mapTags.put("toptags", tags);
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate("freemarker/toptags.ftl");
            MyFreeMarker.generator(template, "toptags.html", mapTags);
        }catch (Exception e) {
            log.error("Hot tags generator exception:" + e.toString());
        }
    }
}
